"""
@file: __init__.py.py
@author：wang
@time: 2022/2/23 0023 13:58
"""
import json
import random
import re

from flask import request, g
from flask_restful import abort
from ronglian_sms_sdk import SmsSDK

from exts import cache
from apps.models.user_models import User

accId = '8a216da873cec132017424b5b8c91fed'
accToken = '4644f2c375cd403280cfa7ab533072fb'
appId = '8a216da873cec132017424b5b9d51ff4'


# 发送手机验证码  短信发送平台:https://www.yuntongxun.com/
def send_message(mobile):
    """
    发送手机验证码
    :param mobile: 要发送的手机号码
    :return:
    """
    sdk = SmsSDK(accId, accToken, appId)
    tid = '1'
    code = random.randint(1000, 9999)
    mobile = mobile
    data = (f'{code}',)
    resp = sdk.sendMessage(tid, mobile, data)
    return resp, code


def get_content(s):
    """
    提取发送成功的状态码
    :param s: 短信接口传入的resp
    :return:
    """
    ret = re.search(r'{"statusCode":".*?"}}', s)
    res = ret.group()
    req = json.loads(res)
    return req["statusCode"]


def check_user():
    """
    检测用户是否存在token令牌
    :return:
    """
    auth = request.headers.get("Authorization")  # 需要携带令牌
    if not auth:
        abort(401, msg="请先登录")
    mobile = cache.get(auth)
    if not mobile:
        abort(401, msg="令牌无效")

    user = User.query.filter(User.phone == mobile).first()
    if not user:
        abort(401, msg="此用户不存在")

    g.user = user


# 验证用户是否进行登录
def login_required(func):
    """
    登录校验装饰器
    """

    def wrapper(*args, **kwargs):
        check_user()
        return func(*args, **kwargs)

    return wrapper
